package com.farm;

import com.farm.chain.*;
import com.farm.command.StartWorkCommand;
import com.farm.decorator.GPSDecorator;
import com.farm.equipment.Equipment;
import com.farm.equipment.factory.EquipmentFactory;
import com.farm.equipment.factory.HarvesterMachineFactory;
import com.farm.equipment.factory.SeedingMachineFactory;
import com.farm.facade.FarmSystemFacade;
import com.farm.monitor.*;
import com.farm.path.*;
import  com.farm.proxy.*;
import java.util.Scanner;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Main {
    private static Scanner scanner = new Scanner(System.in);
    private static EquipmentFactory factory;
    private static Equipment currentEquipment;
    private static FarmSystemFacade facade;
    private static EnvironmentSensor sensor;
    private static PathFinder pathFinder;
    private static ScheduledExecutorService scheduler;
    private static boolean isAutoMonitoring = false;
    private static Random random = new Random();

    public static void main(String[] args) {
        initializeSystem();
        showMainMenu();
    }

    private static void initializeSystem() {
        // 初始化系统组件
        factory = new SeedingMachineFactory();
        facade = new FarmSystemFacade();
        sensor = new EnvironmentSensor();
        pathFinder = new PathFinder(new AStarPathStrategy());
        
        // 注册传感器观察者
        sensor.registerObserver(new TemperatureMonitor());
        sensor.registerObserver(new HumidityMonitor());
        sensor.registerObserver(new PressureMonitor());
    }

    private static void showMainMenu() {
        while (true) {
            System.out.println("\n=== 智能农机管理系统 ===");
            System.out.println("1. 农机设备管理");
            System.out.println("2. 环境监测");
            System.out.println("3. 路径规划");
            System.out.println("4. 任务执行");
            System.out.println("5. 系统管理");
            System.out.println("0. 退出系统");
            System.out.print("请选择功能 (0-5): ");

            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    equipmentManagement();
                    break;
                case 2:
                    environmentMonitoring();
                    break;
                case 3:
                    pathPlanning();
                    break;
                case 4:
                    taskExecution();
                    break;
                case 5:
                    systemManagement();
                    break;
                case 0:
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重试！");
            }
        }
    }

    private static void equipmentManagement() {
        while (true) {
            System.out.println("\n=== 农机设备管理 ===");
            System.out.println("1. 创建新设备");
            System.out.println("2. 查看设备状态");
            System.out.println("3. 控制设备");
            System.out.println("4. 添加GPS功能");
            System.out.println("0. 返回主菜单");
            System.out.print("请选择操作 (0-4): ");

            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    createEquipment();
                    break;
                case 2:
                    checkEquipmentStatus();
                    break;
                case 3:
                    controlEquipment();
                    break;
                case 4:
                    addGPSFeature();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("无效选择，请重试！");
            }
        }
    }

    private static void createEquipment() {
        System.out.println("\n=== 创建新设备 ===");
        System.out.println("1. 播种机");
        System.out.println("2. 收割机");
        System.out.print("请选择设备类型 (1-2): ");
        
        int type = scanner.nextInt();
        System.out.print("请输入设备ID: ");
        String id = scanner.next();
        System.out.print("请输入设备名称: ");
        String name = scanner.next();

        if (type == 1) {
            factory = new SeedingMachineFactory();
        } else {
            factory = new HarvesterMachineFactory();
        }
        currentEquipment = factory.createEquipment(id, name);
        System.out.println("设备创建成功！");
    }

    private static void checkEquipmentStatus() {
        if (currentEquipment == null) {
            System.out.println("请先创建设备！");
            return;
        }
        System.out.println("\n=== 设备状态 ===");
        System.out.println("设备ID: " + currentEquipment.getId());
        System.out.println("设备名称: " + currentEquipment.getName());
        System.out.println("设备状态: " + currentEquipment.getState());
        System.out.println("油量: " + currentEquipment.getFuelLevel() + "%");
        System.out.println("位置: " + currentEquipment.getLocation());
    }

    private static void controlEquipment() {
        if (currentEquipment == null) {
            System.out.println("请先创建设备！");
            return;
        }
        System.out.println("\n=== 控制设备 ===");
        System.out.println("1. 启动设备");
        System.out.println("2. 停止设备");
        System.out.println("3. 设置油量");
        System.out.println("4. 设置位置");
        System.out.print("请选择操作 (1-4): ");

        int choice = scanner.nextInt();
        switch (choice) {
            case 1:
                new StartWorkCommand(currentEquipment).execute();
                break;
            case 2:
                currentEquipment.stop();
                break;
            case 3:
                System.out.print("请输入油量 (0-100): ");
                double fuel = scanner.nextDouble();
                currentEquipment.setFuelLevel(fuel);
                break;
            case 4:
                System.out.print("请输入位置: ");
                String location = scanner.next();
                currentEquipment.setLocation(location);
                break;
        }
    }

    private static void addGPSFeature() {
        if (currentEquipment == null) {
            System.out.println("请先创建设备！");
            return;
        }
        currentEquipment = new GPSDecorator(currentEquipment);
        System.out.println("GPS功能添加成功！");
    }

    private static void environmentMonitoring() {
        while (true) {
            System.out.println("\n=== 环境监测 ===");
            System.out.println("1. 查看当前环境数据");
            System.out.println("2. 更新环境数据");
            System.out.println("3. 开启自动检测");
            System.out.println("4. 关闭自动检测");
            System.out.println("0. 返回主菜单");
            System.out.print("请选择操作 (0-4): ");

            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    System.out.println("当前环境数据：");
                    sensor.notifyObservers();
                    break;
                case 2:
                    manualUpdateEnvironmentData();
                    break;
                case 3:
                    startAutoMonitoring();
                    break;
                case 4:
                    stopAutoMonitoring();
                    break;
                case 0:
                    if (isAutoMonitoring) {
                        stopAutoMonitoring();
                    }
                    return;
            }
        }
    }

    private static void manualUpdateEnvironmentData() {
        System.out.print("请输入温度: ");
        double temp = scanner.nextDouble();
        System.out.print("请输入湿度: ");
        double humidity = scanner.nextDouble();
        System.out.print("请输入气压: ");
        double pressure = scanner.nextDouble();
        sensor.setMeasurements(temp, humidity, pressure);
    }

    private static void startAutoMonitoring() {
        if (isAutoMonitoring) {
            System.out.println("自动检测已经在运行中！");
            return;
        }

        System.out.println("开启自动环境检测...");
        isAutoMonitoring = true;
        
        // 创建定时任务执行器
        scheduler = Executors.newSingleThreadScheduledExecutor();
        
        // 每5秒执行一次检测
        scheduler.scheduleAtFixedRate(() -> {
            if (!isAutoMonitoring) {
                return;
            }
            
            // 生成随机数据
            double temp = 20 + random.nextDouble() * 15; // 20-35度
            double humidity = 40 + random.nextDouble() * 40; // 40-80%
            double pressure = 1000 + random.nextDouble() * 30; // 1000-1030hPa
            
            System.out.println("\n=== 自动检测数据更新 ===");
            System.out.println("时间: " + java.time.LocalTime.now());
            sensor.setMeasurements(temp, humidity, pressure);
            
        }, 0, 5, TimeUnit.SECONDS);
        
        System.out.println("自动检测已启动，每5秒更新一次数据");
    }

    private static void stopAutoMonitoring() {
        if (!isAutoMonitoring) {
            System.out.println("自动检测未在运行！");
            return;
        }

        System.out.println("正在停止自动检测...");
        isAutoMonitoring = false;
        
        if (scheduler != null) {
            scheduler.shutdown();
            try {
                if (!scheduler.awaitTermination(1, TimeUnit.SECONDS)) {
                    scheduler.shutdownNow();
                }
            } catch (InterruptedException e) {
                scheduler.shutdownNow();
            }
        }
        
        System.out.println("自动检测已停止");
    }

    private static void pathPlanning() {
        while (true) {
            System.out.println("\n=== 路径规划 ===");
            System.out.println("1. A*算法规划");
            System.out.println("2. Dijkstra算法规划");
            System.out.println("3. 广度优先算法规划");
            System.out.println("0. 返回主菜单");
            System.out.print("请选择算法 (0-3): ");

            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    pathFinder.setStrategy(new AStarPathStrategy());
                    break;
                case 2:
                    pathFinder.setStrategy(new DijkstraPathStrategy());
                    break;
                case 3:
                    pathFinder.setStrategy(new BreadthFirstStrategy());
                    break;
                case 0:
                    return;
            }
            if (choice >= 1 && choice <= 3) {
                System.out.print("请输入起点: ");
                String start = scanner.next();
                System.out.print("请输入终点: ");
                String end = scanner.next();
                System.out.println(pathFinder.findPath(start, end));
            }
        }
    }

    private static void taskExecution() {
        System.out.println("\n=== 任务执行 ===");
        facade=new FarmSystemFacade(currentEquipment,pathFinder);
        facade.startFarmOperation();
        System.out.println("\n按Enter键继续...");
        scanner.nextLine();
        scanner.nextLine();
        facade.stopFarmOperation();
    }

    private static void systemManagement() {
        while (true) {
            System.out.println("\n=== 系统管理 ===");
            System.out.println("1. 处理系统请求");
            System.out.println("2. 查看系统日志");
            System.out.println("0. 返回主菜单");
            System.out.print("请选择操作 (0-2): ");

            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    handleSystemRequest();
                    break;
                case 2:
                    System.out.println("系统日志：");
                    System.out.println("- 设备操作记录");
                    System.out.println("- 环境数据记录");
                    System.out.println("- 路径规划记录");
                    break;
                case 0:
                    return;
            }
        }
    }

    private static void handleSystemRequest() {
        Handler logHandler = new LogHandler();
        Handler alertHandler = new AlertHandler();
        Handler emergencyHandler = new EmergencyHandler();
        logHandler.setNextHandler(alertHandler);
        alertHandler.setNextHandler(emergencyHandler);

        System.out.println("\n=== 处理系统请求 ===");
        System.out.println("1. 普通请求");
        System.out.println("2. 警告请求");
        System.out.println("3. 紧急请求");
        System.out.print("请选择请求类型 (1-3): ");

        int type = scanner.nextInt();
        String requestType;
        switch (type) {
            case 1:
                requestType = "LOG";
                break;
            case 2:
                requestType = "ALERT";
                break;
            case 3:
                requestType = "EMERGENCY";
                break;
            default:
                System.out.println("无效选择！");
                return;
        }

        System.out.print("请输入请求内容: ");
        String content = scanner.next();
        Request request = new Request(requestType, content);
        logHandler.handleRequest(request);
    }
} 